package com.lei2j;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@SpringBootApplication
@EnableDiscoveryClient
@RestController
@EnableHystrix
public class RibbonApplication
{
    public static void main( String[] args ){
        SpringApplication.run(RibbonApplication.class,args);
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Autowired
    private TestService testService;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/test")
    public String test(@RequestParam("name")String name){
        return testService.test(name);
    }

    @Service
    public class TestService {

        @HystrixCommand(fallbackMethod = "fallback")
        public String test(String name){
            //调用远程服务
            return restTemplate.getForObject("http://client/test?name="+name,String.class);
        }

        public String fallback(String name){
            return "fallback";
        }
    }
}
